<?php
namespace App\GraphQL\Mutations\FactoryDevice;

use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use App\Models\FactoryDevice;
use Illuminate\Support\Facades\Validator;
use App\Models\DeviceOrder;

class Archive
{

    /**
     * Return a value for the field.
     *
     * @param null $rootValue
     *            Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param mixed[] $args
     *            The arguments that were passed into the field.
     * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context
     *            Arbitrary data that is shared between all fields of a single query.
     * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo
     *            Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $this->validate($args);
        $query = FactoryDevice::whereIn('id', $args['devices']);
        $authUser = auth()->user();
        if ($authUser->role->code != 'ADMIN') {
            $query->where('user_id', $authUser->id);
        }

        $query->update([
            'status' => 'ALREADY',
            'device_order_id' => $args['device_order_id']
        ]);
        return [
            'status' => '200',
            'message' => '设备归档成功'
        ];
    }

    public function validate($data)
    {
        $rules = [
            'devices' => [
                'required',
                'array'
            ],
            'devices.*' => [
                'required',
                'numeric'
            ],
            'device_order_id' => [
                'required',
                'numeric'
            ],
        ];
        $messages = [
            'devices.required' => '设备列表不能为空',
            'devices.array' => '设备列表为数组',
            'devices.*.required' => '设备列表ID不能为空',
            'devices.*.numeric' => '设备列表ID为数值',
            'device_order_id.required' => '订单不能为空',
            'device_order_id.numeric' => '订单ID为数值',
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        $order = DeviceOrder::find($data['device_order_id']);
        if(!$order){
            throw new \Exception('订单不存在');
        }
        if($order->status !== 'WAIT_DELIVERY'){
            throw new \Exception('订单状态不能操作');
        }
        return true;
    }
}
